﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using ComboBox = System.Windows.Forms.ComboBox;
using DevExpress.XtraBars;

namespace WCFMINERP.ComControls
{
    using DevExpress.XtraGrid.Views.Grid;
    using DevExpress.XtraGrid.Views.Grid.ViewInfo;

    public static class DevControlExtension
    {
        internal static Form FindFormInternal(this Control control)
        {
            while (control != null && !(control is Form))
            {
                control = control.Parent;
            }
            return (Form)control;
        }
        public static GridHitInfo GetHitInfo(this GridView v)
        {
            Point childAtPoint = v.GridControl.PointToClient(System.Windows.Forms.Cursor.Position);
            return v.CalcHitInfo(childAtPoint);
        }
        public static T GetSelectItemOfType<T>(this ComboBoxEdit comboBox)
        {
            object selectItem = comboBox.SelectedItem;
            if (selectItem is DisplayItem)
            {
                if (selectItem is T)
                {
                    return (T)selectItem;
                }
                DisplayItem displayItem = selectItem as DisplayItem;
                return (T)displayItem.Value;
            }
            int aaaaa = 0;
            if (selectItem is EnumItem)
            {
                int value = ((EnumItem)selectItem).Value;
                string str = ((EnumItem)selectItem).Description;
                DisplayItem displayItem = new DisplayItem(value, str);
                return (T)displayItem.Value;

            }
            return default(T);
        }
        public static void FillCollections<T>(this ComboBoxEdit ctrl, IEnumerable<T> collection, Func<T, string> getDisplayField,
                                            Func<T, object> getVal = null, bool selectOne = true, Func<T, object> orderby = null, Func<T, string> getDisplayField2 = null)
        {
            List<DisplayItem> dataSource = null;
            if (ctrl.Properties != null)
            {
                ctrl.Properties.BeginUpdate();
                dataSource = ctrl.Properties.Items.FillComboBoxItemCollection(collection, getDisplayField, getVal, null, @orderby, getDisplayField2);
                ctrl.Properties.EndUpdate();
            }
            if (selectOne)
            {
                ctrl.SelectedIndex = 0;
            }
            if (ctrl is IDisplaySource)
            {
                IDisplaySource displaySource = ctrl as IDisplaySource;
                if (dataSource != null)
                {
                    displaySource.DisplayItemSource = dataSource.ToArray();
                }
            }
        }
        public static void EnableComboBoxItem<T>(this CheckedComboBoxEdit ctrl, Func<T, CheckedListBoxItem, bool> where) where T : class
        {
            for (int i = 0; i < ctrl.Properties.Items.Count; i++)
            {
                CheckedListBoxItem c = ctrl.Properties.Items[i];
                DisplayItem cc = c.Value as DisplayItem;
                if (cc == null)
                {
                    T foo = c as T;
                    if (foo != null)
                    {
                        c.Enabled = where(foo, c);
                    }
                }
                else
                {
                    T foo = cc.Value as T;
                    c.Enabled = where(foo, c);
                }
            }
        }
        public static void FillComboBoxItemCollection(this ComboBoxItemCollection col, IEnumerable<DisplayItem> src)
        {
            col.Clear();
            if (src != null)
            {
                foreach (DisplayItem item in src)
                {
                    if (item != null)
                    {
                        col.Add(item);
                    }
                }
            }
        }
        public static void FillComboBoxItemCollection(this ComboBox.ObjectCollection col, IEnumerable<DisplayItem> src)
        {
            col.Clear();
            if (src != null)
            {
                foreach (DisplayItem item in src)
                {
                    if (item != null)
                    {
                        col.Add(item);
                    }
                }
            }
        }
        public static List<DisplayItem> FillCollections<T>(this CheckedComboBoxEdit ctrl, IEnumerable<T> collection,
                                                            Func<T, string> getDisplayField, Func<T, object> getVal = null, bool selectOne = false, Func<T, object> orderby = null)
        {
            List<DisplayItem> dataSource = null;
            if (ctrl.Properties != null)
            {
                ctrl.Properties.BeginUpdate();
                dataSource = ctrl.Properties.Items.FillComboBoxItemCollection(collection, getDisplayField, getVal, null, @orderby);
                ctrl.Properties.EndUpdate();
            }
            if (selectOne)
            {
                //ctrl.Properties.Items
            }
            if (ctrl is IDisplaySource)
            {
                IDisplaySource displaySource = ctrl as IDisplaySource;
                if (dataSource != null)
                {
                    displaySource.DisplayItemSource = dataSource.ToArray();
                }
            }
            return dataSource;
        }
        public static void FillComboBoxItemCollection(this CheckedListBoxItemCollection col, IEnumerable<DisplayItem> src)
        {
            col.Clear();
            if (src != null)
            {
                foreach (DisplayItem item in src)
                {
                    if (item != null)
                    {
                        col.Add(item);
                    }
                }
            }
        }
        public static T GetSelectObjectItemOfType<T>(this ToolStripComboBox comboBox)
        {
            object selectItem = comboBox.SelectedItem;
            if (selectItem is DisplayItem)
            {
                if (selectItem is T)
                {
                    return (T)selectItem;
                }
                DisplayItem displayItem = selectItem as DisplayItem;
                return (T)displayItem.Value;
            }
            return default(T);
        }
        public static T GetSelectObjectItemOfType<T>(this BarEditItem item)
        {
            object selectItem = (item.EditValue);
            if (selectItem is DisplayItem)
            {
                if (selectItem is T)
                {
                    return (T)selectItem;
                }
                DisplayItem displayItem = selectItem as DisplayItem;
                return (T)displayItem.Value;
            }
            return default(T);
        }
        public static List<DisplayItem> FillComboBoxItemCollection<T>(this ComboBoxItemCollection col, IEnumerable<T> src,
                                                                    Func<T, string> getDisplayField, Func<T, object> getVal = null, Func<DisplayItem, object> convert = null,
                                                                    Func<T, object> orderby = null, Func<T, string> getDisplayField2 = null)
        {
            col.Clear();
            List<DisplayItem> datasource = new List<DisplayItem>();
            if (src != null)
            {
                T[] enumerable = src as T[] ?? src.ToArray();
                if (@orderby != null)
                {
                    enumerable = enumerable.OrderBy(@orderby).ToArray();
                }
                foreach (T item in enumerable)
                {
                    DisplayItem data = new DisplayItem(getVal == null ? item : getVal(item), getDisplayField(item), null, convert);
                    if (getDisplayField2 != null)
                    {
                        data.DisplayValue1 = getDisplayField2(item);
                    }
                    datasource.Add(data);
                    if (item != null)
                    {
                        col.Add(data);
                    }
                }
            }
            return datasource;
        }
        public static List<T> GetCheckedObjectItemOfType<T>(this CheckedComboBoxEdit comboBox)
        {
            List<T> returnList = new List<T>();
            foreach (object item in comboBox.Properties.Items)
            {
                CheckedListBoxItem checkedListBoxItem = (CheckedListBoxItem)item;
                if (checkedListBoxItem.CheckState == CheckState.Checked && checkedListBoxItem.Enabled)
                {
                    object selectItem = checkedListBoxItem.Value;
                    if (selectItem is DisplayItem)
                    {
                        if (selectItem is T)
                        {
                            returnList.Add((T)selectItem);
                        }
                        else
                        {
                            DisplayItem displayItem = selectItem as DisplayItem;
                            returnList.Add((T)displayItem.Value);
                        }
                    }
                    else
                    {
                        returnList.Add((T)selectItem);
                    }
                }
            }
            return returnList;
        }
        public static List<DisplayItem> FillComboBoxItemCollection<T>(this CheckedListBoxItemCollection col, IEnumerable<T> src,
                                                                    Func<T, string> getDisplayField, Func<T, object> getVal = null, Func<DisplayItem, object> convert = null,
                                                                    Func<T, object> orderby = null)
        {
            col.Clear();
            List<DisplayItem> datasource = new List<DisplayItem>();
            if (src != null)
            {
                T[] enumerable = src as T[] ?? src.ToArray();
                if (@orderby != null)
                {
                    enumerable = enumerable.OrderBy(@orderby).ToArray();
                }
                foreach (T item in enumerable)
                {
                    DisplayItem data = new DisplayItem(getVal == null ? item : getVal(item), getDisplayField(item), null, convert);
                    datasource.Add(data);
                    if (item != null)
                    {
                        col.Add(data);
                    }
                }
            }
            return datasource;
        }
        //
        //        public static void SetSelectItem(this ComboBoxEdit ctrl, string displayfield) {
        //            if (displayfield == null) ctrl.SelectedIndex = 0;
        //            foreach (object c in ctrl.Properties.Items) {
        //                DisplayItem cc = c as DisplayItem;
        //                if (cc.DisplayField == displayfield) {
        //                    ctrl.SelectedItem = c;
        //                    return;
        //                }
        //            }
        //        }
        //
        public static void SetSelect<T>(this ComboBoxEdit ctrl, Func<T, bool> where) where T : class
        {
            if (where == null)
            {
                ctrl.EditValue = null;
                return;
            }
            foreach (object c in ctrl.Properties.Items)
            {
                DisplayItem cc = c as DisplayItem;
                if (cc == null)
                {
                    T foo = c as T;
                    if (foo != null)
                    {
                        if (where(foo))
                        {
                            ctrl.SelectedItem = c;
                            ctrl.ClosePopup();
                            return;
                        }
                    }
                }
                else
                {
                    T foo = cc.Value as T;
                    if (where(foo))
                    {
                        ctrl.SelectedItem = c;
                        ctrl.ClosePopup();
                        return;
                    }
                }
            }
        }
        public static void SetSelectItem(this ComboBoxEdit ctrl, object item)
        {
            if (item == null)
            {
                ctrl.EditValue = null;
                return;
            }
            foreach (object c in ctrl.Properties.Items)
            {
                DisplayItem cc = c as DisplayItem;
                if (cc == null)
                {
                    if (c == item)
                    {
                        ctrl.SelectedItem = c;
                        return;
                    }
                }
                else
                {
                    if (cc.Value.Equals(item) || cc.Equals(item))
                    {
                        ctrl.SelectedItem = c;
                        return;
                    }
                }
            }
        }
        //
        //        public static IEnumerable<DisplayItem> FillItem<T>(this ComboBoxEdit ctrl, IEnumerable<T> data) {
        //            IEnumerable<DisplayItem> items;
        //            if (typeof(T) == typeof(DisplayItem)) items = (IEnumerable<DisplayItem>)data;
        //            else items = ConvertDisplayItem(data);
        //            if (ctrl.Properties != null) {
        //                ctrl.Properties.BeginUpdate();
        //                ctrl.Properties.Items.Clear();
        //                foreach (DisplayItem item in items) {
        //                    ctrl.Properties.Items.Add(item);
        //                }
        //                ctrl.Properties.EndUpdate();
        //            }
        //            ctrl.SelectedIndex = 0;
        //            return items;
        //        }
        //
        //        public static void FillEnum<T>(this CheckedComboBoxEdit comboBox) {
        //            Array arr = Enum.GetValues(typeof(T));
        //            comboBox.Properties.BeginUpdate();
        //            foreach (object a in arr) {
        //                string strText = GetEnumDesc((Enum)a);
        //                DisplayItem item = new DisplayItem { DisplayField = strText, Value = (T)a };
        //                comboBox.Properties.Items.Add(item);
        //            }
        //            comboBox.Properties.EndUpdate();
        //        }
        public static void SetEnumValue(this ComboBoxEdit ctrl, int value)
        {
            foreach (object c in ctrl.Properties.Items)
            {
                EnumItem cc = (EnumItem)c;
                if (cc.Value == value)
                {
                    ctrl.SelectedItem = c;
                    return;
                }
            }
        }
        public static EnumItem GetEnumValue(this ComboBoxEdit ctrl)
        {
            try
            {
                return (EnumItem)ctrl.SelectedItem;
            }
            catch (Exception)
            {
                return new EnumItem() { Value = -1 };
            }
        }

        public static void ExportToExcel(this DevExpress.XtraGrid.GridControl gridControl, IWin32Window owner,string inFileName=null)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.Filter = "Excel文件(*.xls)|*.xls";
            if (!string.IsNullOrEmpty(inFileName))
            {
                fileDialog.FileName = inFileName;
            }
            DialogResult dialogResult = fileDialog.ShowDialog(owner);
            if (dialogResult == DialogResult.OK)
            {
                DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                gridControl.ExportToXls(fileDialog.FileName);
                DevExpress.XtraEditors.XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
       
        public static void FillEnum<T>(this ComboBoxEdit comboBox, Func<int, bool> condition = null, bool addAllItem = false)
        {
            EnumItem[] arr = typeof(T).ConvertEnumItem();
            if (condition != null)
            {
                arr = arr.Where(c => condition(c.Value)).ToArray();
            }
            comboBox.Properties.BeginUpdate();
            if (addAllItem)
            {
                comboBox.Properties.Items.Add(new EnumItem(-1, "(全部)"));
            }
            comboBox.Properties.Items.AddRange(arr);
            comboBox.Properties.EndUpdate();
        }

        #region ComboBoxEdit

        /// <summary>
        ///     根据ComboBoxEdit的Value，获取Index
        /// </summary>
        /// <param name="cbe">控件的名子</param>
        /// <param name="Value">Value值</param>
        /// <returns></returns>
        public static int GetComboboxEditIndex(this ComboBoxEdit cbe, int Value)
        {
            for (int i = 0; i < cbe.Properties.Items.Count; i++)
            {
                int id = Convert.ToInt32((cbe.Properties.Items[i] as DisplayItem).Value);
                if (id == Value)
                {
                    return i;
                }
            }
            return 0;
        }
        public static void FillEnum<T>(this ComboBoxItemCollection comboBox)
        {
            EnumItem[] arr = typeof(T).ConvertEnumItem();
            comboBox.AddRange(arr);
        }
        /// <summary>
        ///     根据ComboBoxEdit的Value，获取Index
        /// </summary>
        /// <param name="cbe">控件的名子</param>
        /// <param name="Value">Value值</param>
        /// <returns></returns>
        public static int GetComboboxEditIndex(ComboBoxEdit cbe, string Value)
        {
            for (int i = 0; i < cbe.Properties.Items.Count; i++)
            {
                string id = Convert.ToString((cbe.Properties.Items[i] as DisplayItem).Value);
                if (id == Value)
                {
                    return i;
                }
            }
            return 0;
        }
        /// <summary>
        ///     根据ComboBoxEdit的DisplayField，获取Index
        /// </summary>
        /// <param name="cbe">控件的名子</param>
        /// <param name="Value">Value值</param>
        /// <returns></returns>
        public static int GetComboboxEditNameIndex(ComboBoxEdit cbe, string DisplayField)
        {
            for (int i = 0; i < cbe.Properties.Items.Count; i++)
            {
                string id = Convert.ToString((cbe.Properties.Items[i] as DisplayItem).DisplayField);
                if (id == DisplayField)
                {
                    return i;
                }
            }
            return 0;
        }
        /// <summary>
        ///     取值
        /// </summary>
        /// <param name="cbe">控件的名子</param>
        /// <returns></returns>
        public static DisplayItem GetComboBoxEdit(ComboBoxEdit cbe)
        {
            return cbe.SelectedItem as DisplayItem;
        }

        #endregion

        #region PictureEdit

        /// <summary>
        ///     根据image完全路径,转换为能存入数据库的类型
        /// </summary>
        /// <param name="fileName">完全路径</param>
        /// <returns></returns>
        public static byte[] SetImageToByteArray(string fileName)
        {
            //Resources._null;
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open);
                int streamLength = (int)fs.Length;
                byte[] image = new byte[streamLength];
                fs.Read(image, 0, streamLength);
                fs.Close();
                return image;
            }
            catch (Exception ee)
            {
                throw ee.InnerException;
            }
        }
        /// <summary>
        ///     将byte[]转为Image类型
        /// </summary>
        /// <param name="mybyte"></param>
        /// <returns></returns>
        public static Image SetByteToImage(byte[] mybyte)
        {
            MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
            Image image = Image.FromStream(mymemorystream);
            return image;
        }
        /// <summary>
        ///     把image转换为byte[]
        /// </summary>
        /// <param name="mybyte"></param>
        /// <returns></returns>
        public static byte[] ConvertImage(Image image)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Icon);
                return ms.ToArray();
            }
            catch (Exception ee)
            {
                throw ee.InnerException;
            }
        }

        #endregion

        #region 文本框输入限制,只能为数字

        /// <summary>
        ///     文本框输入限制,只能为数字
        /// </summary>
        /// <param name="e"></param>
        public static void SetUpInt32(KeyPressEventArgs e)
        {
            ////判断只能输入数字
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == (int)Keys.Back || e.KeyChar == (int)Keys.Space)
            {
                e.Handled = false;
            }
        }

        #endregion
    }
}
